<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>优惠券管理 - 后台管理系统</title>
		<!-- 引入Element UI样式 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<!-- 引入Font Awesome -->
		<link rel="stylesheet"
			href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<!-- 引入Vue -->
		<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
		<!-- 引入Element UI组件库 -->
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>
		<!-- 引入Axios -->
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<script src="../js/authChecker.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
				background-color: #f5f7fa;
				font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
			}

			.container {
				padding: 20px;
				box-sizing: border-box;
			}

			.page-title {
				font-size: 18px;
				font-weight: 500;
				color: #1f2329;
				margin-bottom: 20px;
				padding-bottom: 10px;
				border-bottom: 1px solid #e4e7ed;
			}

			.toolbar {
				margin-bottom: 15px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				flex-wrap: wrap;
				gap: 10px;
			}

			.search-container {
				width: 300px;
				min-width: 200px;
				display: flex;
				/* 子元素水平排列 */
				align-items: center;
				/* 垂直居中对齐 */
				gap: 10px;
				/* （可选）替代 margin，更简洁的间距控制 */
			}

			.action-buttons {
				display: flex;
				gap: 10px;
			}

			.table-container {
				background-color: #fff;
				border-radius: 4px;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
				overflow: hidden;
			}

			.pagination-container {
				margin-top: 15px;
				text-align: right;
			}

			.upload-tip {
				margin-top: 10px;
				color: #606266;
				font-size: 12px;
			}

			/* 统一按钮颜色 - 匹配左侧树形框粉色 #FF1493 */
			.el-button--primary {
				background-color: #FF1493 !important;
				border-color: #FF1493 !important;
			}

			.el-button--primary:hover,
			.el-button--primary:focus {
				background-color: #e60080 !important;
				border-color: #e60080 !important;
			}

			/* 表格样式调整 - 匹配themes.html的表格样式 */
			.el-table th {
				background-color: #d8d8d9 !important;
				/* 灰色表头 */
				color: black !important;
				/* 黑色文字 */
				font-weight: bold !important;
				border: 1px solid #ccc !important;
			}

			.el-table__header-wrapper .el-table__header {
				border-bottom: 1px solid #ccc !important;
				/* 去掉粉色底线 */
			}

			.el-table--striped .el-table__body tr.el-table__row--striped td {
				background-color: #f9f9f9 !important;
				/* 偶数行灰色 */
			}

			.el-table__body tr.current-row>td {
				background-color: #f1f1f1 !important;
				/* 当前行灰色 */
			}

			.el-table__body tr.hover-row>td {
				background-color: #f1f1f1 !important;
				/* 悬停行灰色 */
			}

			.el-table td {
				border: 1px solid #ccc !important;
				/* 单元格边框 */
			}

			/* 操作按钮样式调整 - 使文字颜色与图标一致 */
			.edit-btn {
				color: #696969 !important;
				/* 编辑按钮文字颜色（与图标一致） */
			}

			.delete-btn {
				color: #696969 !important;
				/* 删除按钮文字颜色（与图标一致） */
			}

			/* 鼠标悬停时颜色加深 */
			.edit-btn:hover,
			.delete-btn:hover {
				color: #333 !important;
			}

			/* 下拉选择器样式调整 */
			.el-select .el-input.is-focus .el-input__inner {
				border-color: #FF1493 !important;
			}

			.el-select-dropdown__item.selected {
				background-color: #ffe6f0 !important;
				color: #FF1493 !important;
			}

			/* 响应式调整 */
			@media (max-width: 768px) {
				.toolbar {
					flex-direction: column;
					align-items: stretch;
				}

				.search-container {
					width: 100%;
				}

				.action-buttons {
					width: 100%;
					justify-content: flex-end;
				}

				.el-dialog {
					width: 90% !important;
				}
			}
		</style>
	</head>

	<body>
		<div id="app" class="container">
			<!-- 页面标题 -->
			<div class="page-title">优惠券管理</div>

			<!-- 操作工具栏 -->
			<div class="toolbar">
				<div class="search-container">
					<el-select v-model="searchStatus" placeholder="请选择使用范围" clearable @change="handleSearch">
						<el-option label="全场通用" value="0"></el-option>
						<el-option label="指定商品" value="1"></el-option>
					</el-select>

					<!-- 名称模糊查询 -->
					<el-input placeholder="请输入节日名称搜索" v-model="searchKeyword" clearable prefix-icon="el-icon-search"
						@keyup.enter.native="handleSearch" @clear="handleSearch"></el-input>
				</div>



				<div class="action-buttons">
					<el-button type="primary" @click="handleAdd">
						<i class="fa fa-plus"></i> 新增优惠券
					</el-button>
				</div>
			</div>

			<!-- 优惠券列表 -->
			<div class="table-container">
				<el-table :data="coupons" border stripe style="width: 100%;" v-loading="loading">
					<el-table-column prop="discountid" label="ID" width="80" align="center"></el-table-column>

					<el-table-column prop="discountname" label="优惠券名称" min-width="150"></el-table-column>

					<el-table-column prop="money" label="减少金额" min-width="150"></el-table-column>

					<el-table-column prop="maxmoney" label="满多少金额可用" min-width="150"></el-table-column>

					<el-table-column prop="starttime" label="生效时间" width="180" align="center"></el-table-column>

					<el-table-column prop="endtime" label="过期时间" width="180" align="center"></el-table-column>

					<el-table-column prop="status" label="使用范围" min-width="150"
						:formatter="formatStatus"></el-table-column>

					<el-table-column label="操作" width="180" align="center">
						<template slot-scope="scope">
							<!-- 编辑按钮添加自定义类名 -->
							<el-button size="mini" type="text" @click="handleEdit(scope.row)" class="edit-btn">
								<i class="fa fa-pencil" style="color: #696969;"></i> 编辑
							</el-button>
							<!-- 删除按钮添加自定义类名 -->
							<el-button size="mini" type="text" @click="handleDelete(scope.row.discountid)"
								class="delete-btn">
								<i class="fa fa-trash" style="color: #696969;"></i> 删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 分页 -->
			<div class="pagination-container">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="currentPage" :page-sizes="[5]" :page-size="pageSize" :total="total"
					layout="total, sizes, prev, pager, next, jumper"></el-pagination>
			</div>

			<!-- 新增/编辑优惠券对话框 -->
			<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false">
				<el-form :model="form" :rules="rules" ref="form" label-width="120px">
					<el-form-item label="优惠券名称" prop="discountname">
						<el-input v-model="form.discountname" placeholder="请输入优惠券名称"></el-input>
					</el-form-item>

					<el-form-item label="减少金额" prop="money">
						<el-input v-model="form.money" placeholder="请输入减少金额" type="number"></el-input>
					</el-form-item>

					<el-form-item label="满多少可用" prop="maxmoney">
						<el-input v-model="form.maxmoney" placeholder="请输入满多少可用" type="number"></el-input>
					</el-form-item>

					<el-form-item label="生效时间" prop="starttime">
						<el-date-picker v-model="form.starttime" type="date" placeholder="选择生效时间"
							value-format="yyyy-MM-dd"></el-date-picker>
					</el-form-item>

					<el-form-item label="过期时间" prop="endtime">
						<el-date-picker v-model="form.endtime" type="date" placeholder="选择过期时间"
							value-format="yyyy-MM-dd"></el-date-picker>
					</el-form-item>

					<el-form-item label="使用范围" prop="status">
						<el-select v-model="form.status" placeholder="请选择使用范围">
							<el-option label="全场通用" value="0"></el-option>
							<el-option label="指定商品" value="1"></el-option>
						</el-select>
					</el-form-item>

				</el-form>

				<div slot="footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
				</div>
		</div>
		</div>

		<script>
			// 在页面加载时立即检查登录状态
			if (!checkAdminLogin()) {
				// 登录检查失败，阻止页面继续加载
				console.log('登录验证失败，已跳转至登录页');
			} else {
				new Vue({
					el: '#app',
					data() {
						return {
							// 搜索条件（状态：0-全场通用，1-指定商品）
							searchStatus: '',

							// 搜索条件
							searchKeyword: '',

							// 后端基础URL
							baseUrl: 'http://localhost:8887/discount',

							// 分页参数
							currentPage: 1,
							pageSize: 5,
							total: 0,

							// 优惠券数据
							coupons: [],
							loading: false,

							// 对话框相关
							dialogVisible: false,
							dialogTitle: '新增优惠券',
							form: {
								discountid: '', // 优惠券ID
								discountname: '', //优惠券名称
								money: '', // 减少金额
								maxmoney: '', // 满多少可用
								starttime: '', // 生效时间
								endtime: '', // 过期时间
								status: '' // 使用范围（0-全场通用，1-指定商品）
							},
							submitting: false,

							// 表单验证规则
							rules: {
								money: [{
										required: true,
										message: '请输入减少金额',
										trigger: 'blur'
									},
									{
										validator: (rule, value, callback) => {
											const maxmoney = this.form.maxmoney;
											const moneyNum = Number(value);
											const maxmoneyNum = Number(maxmoney);
											if (isNaN(maxmoneyNum)) {
												callback();
												return;
											}
											if (moneyNum > maxmoneyNum) {
												callback(new Error('减少金额不能大于满多少金额可用'));
											} else {
												callback();
											}
										},
										trigger: ['blur', 'change']
									}
								],
								maxmoney: [{
									required: true,
									message: '请输入满多少可用',
									trigger: 'blur'
								}],

								starttime: [{
									required: true,
									message: '请选择生效时间',
									trigger: 'change'
								}],
								endtime: [{
									required: true,
									message: '请选择过期时间',
									trigger: 'change'
								}],
								status: [{
									required: true,
									message: '请选择使用范围',
									trigger: 'change'
								}]
							}
						}
					},

					created() {
						this.fetchCoupons(); // 初始化加载优惠券数据
					},

					methods: {
						// 格式化状态显示
						formatStatus(row, column) {
							const status = String(row.status);
							return status === '0' ? '全场通用' : '指定商品';
						},

						// 获取优惠券列表（分页+状态筛选）
						fetchCoupons() {
							this.loading = true;
							const api = '/selectAllDiscountEnd'; // 统一接口

							axios.get(`${this.baseUrl}${api}`, {
									params: {
										page: this.currentPage, // 分页页码
										pageSize: this.pageSize, // 每页条数（固定5条，与后端对齐）
										discountname: this.searchKeyword, // 名称模糊查询
										status: this.searchStatus // 状态筛选
									}
								})
								.then(response => {
									const formatDate = (timestamp) => {
										if (!timestamp) return '';
										const date = new Date(timestamp);
										return (
											date.getFullYear() + '-' +
											(date.getMonth() + 1).toString().padStart(2, '0') + '-' +
											date.getDate().toString().padStart(2, '0')
										);
									};

									// 响应结构统一：discountList + total
									this.coupons = (response.data.data.discountList || []).map(item => ({
										...item,
										starttime: formatDate(item.starttime),
										endtime: formatDate(item.endtime)
									}));
									this.total = response.data.data.total || 0;
								})
								.catch(error => {
									console.error('获取优惠券列表失败:', error);
									this.$message.error('获取优惠券列表失败');
									this.coupons = [];
									this.total = 0;
								})
								.finally(() => {
									this.loading = false;
								});
						},

						// 搜索触发
						handleSearch() {
							this.currentPage = 1;
							this.fetchCoupons();
						},

						// 分页大小变更
						handleSizeChange(val) {
							this.pageSize = val;
							this.currentPage = 1;
							this.fetchCoupons();
						},

						// 当前页变更
						handleCurrentChange(val) {
							this.currentPage = val;
							this.fetchCoupons();
						},

						// 新增优惠券
						handleAdd() {
							this.dialogTitle = '新增优惠券';
							this.form = {
								discountid: '',
								discountname: '',
								money: '',
								maxmoney: '',
								starttime: '',
								endtime: '',
								status: ''
							};
							this.dialogVisible = true;
							this.$nextTick(() => {
								this.$refs.form && this.$refs.form.clearValidate();
							});
						},

						// 编辑优惠券（回显数据）
						handleEdit(row) {
							this.dialogTitle = '编辑优惠券';
							this.form = {
								discountid: row.discountid,
								discountname: row.discountname,
								money: row.money,
								maxmoney: row.maxmoney,
								starttime: row.starttime,
								endtime: row.endtime,
								status: String(row.status)
							};
							this.dialogVisible = true;
						},

						// 删除优惠券（二次确认）
						handleDelete(discountid) {
							this.$confirm('确定要删除该优惠券吗?', '提示', {
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								type: 'warning'
							}).then(() => {
								axios.post(`${this.baseUrl}/deleteDiscountEnd?discountid=${discountid}`)
									.then(response => {
										if (response.data === '删除成功') {
											this.$message.success('删除成功');
											this.fetchCoupons();
										}
									})
									.catch(error => {
										console.error('删除失败:', error.response?.data);
										this.$message.error('删除失败: ' + (error.response?.data?.message ||
											error.message));
									});
							});
						},

						// 提交表单（新增/编辑）
						handleSubmit() {
							this.$refs.form.validate((valid) => {
								if (valid) {
									if (new Date(this.form.starttime) > new Date(this.form.endtime)) {
										this.$message.error('生效时间不能晚于过期时间！');
										return;
									}

									const money = Number(this.form.money);
									const maxmoney = Number(this.form.maxmoney);
									if (money > maxmoney) {
										this.$message.error('减少金额不能大于满多少金额可用！');
										return;
									}

									this.submitting = true;
									const request = this.form.discountid ?
										axios.post(`${this.baseUrl}/updateDiscountEnd`, this.form) :
										axios.post(`${this.baseUrl}/insertDiscountEnd`, this.form);

									request.then(() => {
											this.$message.success(this.form.discountid ? '编辑成功' : '新增成功');
											this.dialogVisible = false;
											this.fetchCoupons();
										})
										.catch(error => {
											console.error('操作失败:', error);
											this.$message.error('操作失败，请重试');
										})
										.finally(() => {
											this.submitting = false;
										});
								}
							});
						}
					}
				});
			}
		</script>
	</body>
</html>